package com.dd.action;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.zip.GZIPInputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.dd.dao.DdQaDAO;
import com.dd.dao.DdSmsDAO;
import com.dd.dao.LiuDAO;
import com.dd.entity.*;
import com.dd.ma.MaUser;
import com.dd.ma.MaUtil;
import com.dd.ma.PostAction;
import com.dd.util.DateStrFormat;
import com.dd.util.PageList;
import com.dd.util.PubFun;

public class DataAction extends BaseAction {
	private String getCookieStr(String cookie, String agent, String phone,
			String password) {
		String cookiestr = "";
		try {
			// MaUtil.printMsg("模拟登陆......");
			PostAction LoginAction = new PostAction(MaUtil.LONIN_URL, cookie,
					agent);
			NameValuePair[] data1 = {
					new NameValuePair("login_id", MaUtil
							.getSndaRequestString(phone)),
					new NameValuePair("password", MaUtil
							.getSndaRequestString(password)) };
			String res = LoginAction.getActionResponse(data1);
			int pos1 = res.indexOf("<session_id>");
			int pos2 = res.indexOf("</session_id>");
			cookiestr = res.substring(pos1 + 12, pos2);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return cookiestr;
	}

	public String getSndaRequestString(String input) {
		try {
			SecretKeySpec keyspec = new SecretKeySpec("rBwj1MIAivVN222b"
					.getBytes(), "AES");
			Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
			c.init(Cipher.ENCRYPT_MODE, keyspec);
			String output = Base64.encodeBase64String(c.doFinal(input
					.getBytes()));
			if (output.endsWith("=")) {
				output = output.substring(0, output.length() - 1);
			}
			if (output.endsWith("=")) {
				output = output.substring(0, output.length() - 1);
			}
			return output;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return input;
	}

	public String getSndaResponseString(InputStream ins) {
		try {
			GZIPInputStream gis = null;
			gis = new GZIPInputStream(ins);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] b = new byte[0x400];
			int n;
			while ((n = gis.read(b)) != -1)
				baos.write(b, 0, n);
			byte[] bb = baos.toByteArray();
			SecretKeySpec keyspec = new SecretKeySpec("rBwj1MIAivVN222b"
					.getBytes(), "AES");
			Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
			c.init(Cipher.DECRYPT_MODE, keyspec);
			byte[] bbb = c.doFinal(bb);
			String str = new String(bbb, "utf-8");
			return str;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public ActionForward startma(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		try {
			String phone = "";
			String pass = "";
			String cookie = "8dja0u09vd75tijnegrq62mn44";
			String agent = "Million/1.0.1 (iPhone; iPhone3,1; 6.0.1)";
			boolean relogin = false;
			if (request.getParameter("phone") != null) {
				phone = request.getParameter("phone");
			}
			if (request.getParameter("pass") != null) {
				pass = request.getParameter("pass");
			}
			if (request.getParameter("cookie") != null) {
				cookie = request.getParameter("cookie");
				cookie = URLDecoder.decode(cookie, "utf-8");
			}
			if (request.getParameter("agent") != null) {
				agent = request.getParameter("agent");
			}
			if (request.getParameter("relogin") != null
					&& request.getParameter("relogin").equals("1")) {
				relogin = true;
			}
			if(phone.length()!=11){	
				out.println("手机号输入不正确</br>");
				return null;
			}
			if(pass.trim().length()<1){
				if(cookie.length()<10){
					out.println("无密码时候请输入cookie!</br>");
					return null;
				}else{
					out.println("无密码强制不重新登陆!</br>");
					relogin = false;
				}
			}
			Hashtable<String,MaUser> ht;
			ServletContext applaction = request.getSession()
					.getServletContext();
			if(applaction.getAttribute("mausers")!=null){
				ht =  (Hashtable)applaction.getAttribute("mausers");
			}else{
				ht = new Hashtable<String,MaUser> ();
			}
			
			if (!ht.containsKey(phone)) {
				MaUser mu = new MaUser();
				mu.setPhone(phone);
				mu.setPassword(pass);
				mu.setAgent(agent);
				mu.setRelogin(relogin);
				mu.setCookie("S=" + cookie);
				mu.startProcess();
				out.print("定时器添加成功!");
				ht.put(phone, mu);
				applaction.setAttribute("mausers", ht);
			} else {
				MaUser mu =ht.get(phone);
				mu.setRelogin(relogin);
				if(pass.length()>1){
					mu.setPassword(pass);
				}
				if(cookie.length()>5){
					mu.setCookie("S=" + cookie);
				}
				if(agent.length()>5){
					mu.setAgent(agent);
				}
				if (!mu.isAlive()) {
					mu.startProcess();
					out.print(
							"定时器重启成功!");
				} else {
					out.print("定时器已经在运行中!");
				}
				ht.put(phone, mu);
				applaction.setAttribute("mausers", ht);
			}

		} catch (Exception e) {
			e.printStackTrace();
			out.println("出错啦!");
		}
		return null;
	}
	
	public ActionForward stopma(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		try {
			String phone = "";
			if (request.getParameter("phone") != null) {
				phone = request.getParameter("phone");
			}
			if(phone.length()!=11){
				out.println("无手机号输入不正确</br>");
				return null;
			}
			Hashtable<String,MaUser> ht;
			ServletContext applaction = request.getSession()
					.getServletContext();
			if(applaction.getAttribute("mausers")!=null){
				ht =  (Hashtable)applaction.getAttribute("mausers");
			}else{
				ht = new Hashtable<String,MaUser> ();
			}
			
			if (!ht.containsKey(phone)) {
				out.print("定时器不存在!");
			} else {
				MaUser mu = (MaUser) ht.get(phone);
				
				if (mu.isAlive()) {
					mu.stopProcess();
					out.print("定时器停止成功!");
				} else {
					out.print("定时器已经是停止状态!");
				}
				ht.put(phone, mu);
				applaction.setAttribute("mausers", ht);
			}

		} catch (Exception e) {
			e.printStackTrace();
			out.println("出错啦!");
		}
		return null;
	}
	public ActionForward clearma(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		try {
			String phone = "";
			if (request.getParameter("phone") != null) {
				phone = request.getParameter("phone");
			}
			if(phone.length()!=11){
				out.println("无手机号输入不正确</br>");
				return null;
			}
			File f = new File(MaUtil.FILEPATH+phone+"_full.html");
			if(f.exists()){
				f.delete();
			}
			
			f = new File(MaUtil.FILEPATH+phone+".html");
			if(f.exists()){
				f.delete();
			}
			out.println("删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
			out.println("出错啦!");
		}
		return null;
	}
	public ActionForward macookie(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String phone = "13705050638";
			String pass = "s7837750";
			System.out.println(this.getCookieStr("",
					"Million/1.0.1 (iPhone; iPhone3,1; 6.0.1)", phone, pass));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public ActionForward am1(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {

			HttpClient httpClient = new HttpClient();
			String url = "http://game1-cbt.ma.sdo.com:10001/connect/app/exploration/fairybattle?cyt=1";
			PostMethod postMethod = new PostMethod(url);
			postMethod.setRequestHeader("Accept-Encoding", "gzip");
			postMethod.setRequestHeader("Host", "game1-cbt.ma.sdo.com:10001");
			postMethod.setRequestHeader("Content-Type",
					"application/x-www-form-urlencoded");
			postMethod.setRequestHeader("Cookie",
					"S=9qp7j5uf9tndo0frs33itkd0d6");
			postMethod.setRequestHeader("Accept-Language", "zh-cn");
			postMethod.setRequestHeader("User-Agent",
					"Million/1.0.1 (iPhone; iPhone3,1; 6.0.1)");
			NameValuePair[] data = {

					new NameValuePair("serial_id", this
							.getSndaRequestString("17284645")),
					new NameValuePair("user_id", this
							.getSndaRequestString("53024")) };
			// 将表单的值放入postMethod中
			postMethod.setRequestBody(data);
			httpClient.executeMethod(postMethod);
			String str = this.getSndaResponseString(postMethod
					.getResponseBodyAsStream());
			Document doc = DocumentHelper.parseText(str);
			Element rootElm = doc.getRootElement();
			Element header = rootElm.element("header");
			String code = header.element("error").element("code").getText();
			System.out.println(str);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public ActionForward am(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			// String cookiestr = "";
			// try {
			// MaUtil.printMsg("模拟登陆......");
			// PostAction LoginAction = new PostAction(MaUtil.LONIN_URL,
			// "", "Million/1.0.1 (iPhone; iPhone3,1; 6.0.1)");
			// NameValuePair[] data1 = {
			// new NameValuePair("login_id", MaUtil
			// .getSndaRequestString("13705050638")),
			// new NameValuePair("password", MaUtil
			// .getSndaRequestString("s7837750")) };
			// String res = LoginAction.getActionResponse(data1);
			// //System.out.println(res);
			// int pos = res.indexOf("<session_id>");
			// int pos2 = res.indexOf("</session_id>");
			// cookiestr = res.substring(pos+12,pos2);
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			// System.out.println(cookiestr);
			// 8dja0u09vd75tijnegrq62mn44
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			HttpClient httpClient = new HttpClient();
			String url = "http://game1-cbt.ma.sdo.com:10001/connect/app/menu/fairyselect?cyt=1";

			PostMethod postMethod = new PostMethod(url);

			postMethod.setRequestHeader("Accept-Encoding", "gzip");
			postMethod.setRequestHeader("Host", "game1-cbt.ma.sdo.com:10001");
			postMethod.setRequestHeader("Content-Type",
					"application/x-www-form-urlencoded");
			postMethod.setRequestHeader("Cookie",
					"S=kakoo07m5k8l9k3vgq5j0ltd00");
			postMethod.setRequestHeader("Accept-Language", "zh-cn");
			postMethod.setRequestHeader("User-Agent",
					"Million/1.0.1 (iPhone; iPhone3,1; 6.0.1)");

			NameValuePair[] data = {};
			// new NameValuePair("login_id", "/4MAu0LKZc0Zulk7yc5Y+A"),
			// new NameValuePair("password", "N2QiXntzujsMFK3Xu2bbMQ") };
			// 将表单的值放入postMethod中
			postMethod.setRequestBody(data);
			httpClient.executeMethod(postMethod);
			GZIPInputStream gis = null;
			gis = new GZIPInputStream(postMethod.getResponseBodyAsStream());
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] b = new byte[0x400];
			int n;
			while ((n = gis.read(b)) != -1)
				baos.write(b, 0, n);
			byte[] bb = baos.toByteArray();
			SecretKeySpec keyspec = new SecretKeySpec("rBwj1MIAivVN222b"
					.getBytes(), "AES");
			Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
			c.init(Cipher.DECRYPT_MODE, keyspec);
			byte[] bbb = c.doFinal(bb);
			String str = new String(bbb, "utf-8");
			System.out.println(str);
			Document doc = DocumentHelper.parseText(str);
			Element rootElm = doc.getRootElement();
			Element header = rootElm.element("header");
			String code = header.element("error").element("code").getText();
			System.out.println("Error Code:" + code);
			if (!code.equals("0")) {
				return null;
			}
			Element body = rootElm.element("body");
			String remaining_rewards = body.element("fairy_select").element(
					"remaining_rewards").getText();
			System.out.println("remaining_rewards:" + remaining_rewards);
			List<Element> fairy_event = body.element("fairy_select").elements(
					"fairy_event");
			for (int i = fairy_event.size() - 1; i > 0; i--) {
				Element fairy = fairy_event.get(i);
				String user_id = fairy.element("user").element("id").getText();
				String user_name = fairy.element("user").element("name")
						.getText();
				String fairy_serial_id = fairy.element("fairy").element(
						"serial_id").getText();
				String fairy_lv = fairy.element("fairy").element("lv")
						.getText();
				String fairy_name = fairy.element("fairy").element("name")
						.getText();
				String fairy_put_down = fairy.element("put_down").getText();
				String strat_time = fairy.element("start_time").getText()
						+ "000";
				Date date = new Date(Long.parseLong(strat_time));
				String datestr = df.format(date);
				response.getWriter().print(
						"time:" + datestr + "  friend:" + user_name + "("
								+ user_id + ")  name:" + fairy_name + "  id:"
								+ fairy_serial_id + "  lv:" + fairy_lv
								+ "  down:" + fairy_put_down + "</br>");
				System.out.print("time:" + datestr + "  friend:" + user_name
						+ "(" + user_id + ")  name:" + fairy_name + "  id:"
						+ fairy_serial_id + "  lv:" + fairy_lv + "  down:"
						+ fairy_put_down);
				System.out.println();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void jpg(String srcFile, String tarFile) {
		File file = null;
		BufferedImage src = null;
		FileOutputStream out = null;
		ImageWriter imgWrier;
		ImageWriteParam imgWriteParams;

		// 指定写图片的方式为 jpg
		imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
		imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
				null);
		// 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
		imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
		// 这里指定压缩的程度，参数qality是取值0~1范围内，
		imgWriteParams.setCompressionQuality((float) 0.5);
		imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
		ColorModel colorModel = ColorModel.getRGBdefault();
		// 指定压缩时使用的色彩模式
		imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
				colorModel, colorModel.createCompatibleSampleModel(16, 16)));

		try {

			file = new File(srcFile);
			if (new FileInputStream(file).available() < 34577) {
				return;
			}
			src = ImageIO.read(file);
			out = new FileOutputStream(tarFile);
			imgWrier.reset();
			// 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造
			imgWrier.setOutput(ImageIO.createImageOutputStream(out));
			// 调用write方法，就可以向输入流写图片
			imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
			out.flush();
			out.close();

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	public ActionForward test3(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		File dir = new File("C:\\image\\");
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				File[] files2 = files[i].listFiles();
				for (int j = 0; j < files2.length; j++) {
					System.out.println(files2[j].getAbsolutePath());
					this.jpg(files2[j].getAbsolutePath(), files2[j]
							.getAbsolutePath());
				}
			} else {

			}
		}
		return null;
	}

	public ActionForward addsms(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		try {
			String phone[] = request.getParameter("phone").split(",");
			String content = request.getParameter("content");
			// 接受srcphone参数.判断时间是不是已经晚上8点后了,是的话发送短信提示
			System.out.println(request.getParameter("srcphone"));
			if (request.getParameter("srcphone") != null
					&& request.getParameter("srcphone").length() > 10) {
				String srcphone = request.getParameter("srcphone");
				int hour = new Date().getHours();
				if (hour > 19) {
					DdSms dss = new DdSms();
					dss.setCreatedate(new Date());
					dss.setStatus(0);
					dss.setTypes(0);
					dss.setPhone(srcphone);
					dss.setSendmsg("【蛋订网】您的订单我们已收到,由于现在是客服下班时间,我们将在明天为您确认!");
					this.getDdSmsDAO().saveOrUpdate(dss);
				}
			}
			for (int i = 0; i < phone.length; i++) {
				Long l = Long.parseLong(phone[i]);
				DdSms dss = new DdSms();
				dss.setCreatedate(new Date());
				dss.setStatus(0);
				dss.setTypes(0);
				dss.setPhone(l + "");
				dss.setSendmsg(content);
				this.getDdSmsDAO().saveOrUpdate(dss);

			}
			out.print("添加成功");
		} catch (Exception e) {
			out.print("添加失败");
			e.printStackTrace();
			return null;
		}
		return null;
	}

	public ActionForward getPosByKW(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		StringBuffer sbf = new StringBuffer("[");
		try {

			String kw = request.getParameter("kw");// keyword
			if (kw != null && !kw.trim().equals("")) {
				List list = this.getDdKeywordDAO().findPosByKW(kw);
				for (int i = 0; i < list.size(); i++) {
					DdKeyword dk = (DdKeyword) list.get(i);
					if (i == 0) {
						sbf.append("{\"name\":\"" + dk.getKeyword()
								+ "\",\"pos\":\"" + dk.getKeyword2() + "\"}");
					} else {
						sbf.append(",{\"name\":\"" + dk.getKeyword()
								+ "\",\"pos\":\"" + dk.getKeyword2() + "\"}");
					}
				}
			}
			sbf.append("]");
			out.print(sbf.toString());
		} catch (Exception e) {
			out.print("[]");
			e.printStackTrace();
			return null;
		}
		return null;
	}

	public ActionForward test(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();

		return null;
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	// 做汇总统计
	public ActionForward count(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// js传来的referer是前段页面真实的referer
		String referer = request.getParameter("referer");
		if (referer == null || referer.length() < 5) {
			referer = "";
		}
		DdCount dc = new DdCount();
		// 0代表游客
		dc.setUid(Integer.parseInt(request.getParameter("uid")));
		dc.setDate(System.currentTimeMillis());
		dc.setReferer(referer);
		// 这边的referer就是前段用户实际访问的页面
		dc.setUrl(request.getHeader("referer"));
		// 用户实际IP
		dc.setIp(getIpAddr(request));
		this.getDdUserDAO().saveOrUpdateDC(dc);
		return null;
	}

	// 做汇总统计
	public ActionForward count1(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// js传来的referer是前段页面真实的referer
		response.setContentType("text/plain;charset=UTF-8");
		String referer = request.getParameter("referer");
		String jsoncallback = request.getParameter("jsoncallback");
		if (referer == null || referer.length() < 5) {
			referer = "";
		}
		response.setHeader("Cache-Control", "no-cache");
		// HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		DdCount dc = new DdCount();
		// 0代表游客
		dc.setUid(Integer.parseInt(request.getParameter("uid")));
		dc.setDate(System.currentTimeMillis());
		dc.setReferer(referer);
		// 这边的referer就是前段用户实际访问的页面
		dc.setUrl(request.getHeader("referer"));
		// 用户实际IP
		dc.setIp(getIpAddr(request));
		this.getDdUserDAO().saveOrUpdateDC(dc);
		out.println(jsoncallback + "()");
		return null;
	}

	public ActionForward querycount(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		// HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		String logid = String.valueOf((Integer) request.getSession()
				.getAttribute("systemlogid"));// 系统用户是否已经登录
		StringBuffer sbf = new StringBuffer("{");
		if (request.getParameter("tt") != null) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			return null;
		}
		if (logid == null || logid.trim().length() == 0) {// 商家用户尚未登录
			// 返回-1
			out.print("{\"error\":-1}");
			return null;
		}
		try {
			String startdate = request.getParameter("startdate");// 
			String starthour = request.getParameter("starthour");// 
			String enddate = request.getParameter("enddate");// 
			String endhour = request.getParameter("endhour");// 
			String pageNo = request.getParameter("pageno");// 第几页
			String pageSize = request.getParameter("pagesize");// 每页记录数
			String url = request.getParameter("url");// 
			String ip = request.getParameter("ip");// 
			String referer = request.getParameter("referer");// 
			StringBuffer sqlwhere = new StringBuffer();
			// 开始时间
			if (startdate != null && !startdate.equals("")) {
				DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH");
				if (starthour.length() == 1) {
					starthour = "0" + starthour;
				}
				Date date = format1.parse(startdate + " " + starthour);
				sqlwhere.append(" and date>=" + date.getTime());
			}
			if (enddate != null && !enddate.equals("")) {
				DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH");
				if (endhour.length() == 1) {
					endhour = "0" + endhour;
				}
				Date date = format1.parse(enddate + " " + endhour);
				sqlwhere.append(" and date<=" + date.getTime());
			}
			if (url != null && url.trim().length() > 0) {
				sqlwhere.append(" and url like '%" + url + "%'");
			}
			if (referer != null && referer.trim().length() > 0) {
				sqlwhere.append(" and referer like '%" + referer + "%'");
			}
			if (ip != null && ip.trim().length() > 0) {
				sqlwhere.append(" and ip ='" + ip + "' ");
			}
			int i_pageNo = 1;
			if (pageNo != null && pageNo.trim().length() > 0) {
				i_pageNo = Integer.parseInt(pageNo);
			} else {
				i_pageNo = 1;
			}
			int i_pageSize = 10;
			if (pageSize != null && pageSize.trim().length() > 0) {
				i_pageSize = Integer.parseInt(pageSize);
			} else {
				i_pageSize = 10;
			}
			PageList list = this.getDdOrderDAO().findAllCount(
					sqlwhere.toString(), i_pageNo, i_pageSize);
			sbf.append("\"counts\":\"" + list.getTotalCount()
					+ "\",\"count\":[");
			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (int i = 0; i < list.size(); i++) {

				DdCount ds = (DdCount) list.get(i);
				String date = format1.format(new Date(ds.getDate()));
				if (i != 0) {
					sbf.append(",");
				}
				sbf.append("{\"ip\":\"" + ds.getIp() + "\",\"url\":\""
						+ ds.getUrl() + "\",\"referer\":\"" + ds.getReferer()
						+ "\",\"date\":\"" + date + "\"}");
			}
			sbf.append("]}");
			System.out.println(System.currentTimeMillis() + "=="
					+ sbf.toString());
			out.print(sbf.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	// 查找新单
	// 待确认和待消费都找
	public ActionForward queryneworder(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		// HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		try {
			StringBuffer sbf = new StringBuffer("{\"order\":[");
			sbf.append(this.getDdUserDAO().getNewOrder());
			sbf.append("]}");
			out.print(sbf.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	// 确认新单
	// 传入oid,remark(几号桌)
	// 需要加待发短信
	public ActionForward confirmneworder(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		// HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		try {
			String remark = request.getParameter("remark");
			String oid = request.getParameter("oid");
			this.getDdUserDAO().updateNewOrder(oid, remark, 2);
			out.print("{\"sgni\":\"1\"}");
		} catch (Exception e) {
			out.print("{\"sgni\":\"0\"}");
			e.printStackTrace();
			return null;
		}
		return null;
	}

	// 取消新单
	// 传入oid,取消订单(status=-1)
	public ActionForward cancelneworder(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		// HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		try {
			String remark = request.getParameter("remark");
			String oid = request.getParameter("oid");
			this.getDdUserDAO().updateNewOrder(oid, remark, -2);
			out.print("{\"sgni\":\"1\"}");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	// 查询历史订单
	// 可选 sid,uid,fromtime,totime
	public ActionForward queryoldorder(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		// HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		try {
			StringBuffer sbf = new StringBuffer("{\"order\":[");
			sbf.append(this.getDdUserDAO().getNewOrder());
			sbf.append("]}");
			out.print(sbf.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	// 汇总查询
	//
	public ActionForward countorder(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		// HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		try {
			StringBuffer sbf = new StringBuffer("{\"order\":[");
			sbf.append(this.getDdUserDAO().getNewOrder());
			sbf.append("]}");
			out.print(sbf.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	public ActionForward test2(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		List list = this.getDdShopDAO().findAll();
		try {
			for (int i = 0; i < list.size(); i++) {
				DdShop ds = (DdShop) list.get(i);

				StringBuffer sbf = new StringBuffer(ds.getId() + "	"
						+ ds.getName());
				sbf.append("	"
						+ DateStrFormat.getCurrentTime1(ds.getCreatedate()));
				sbf
						.append("	"
								+ DateStrFormat
										.getCurrentTime1(ds.getEnddate()));
				String area = "鼓楼区";
				if (ds.getArea().equals("11102")) {
					area = "台江区";
				}
				if (ds.getArea().equals("11103")) {
					area = "仓山区";
				}
				if (ds.getArea().equals("11104")) {
					area = "晋安区";
				}
				if (ds.getArea().equals("11105")) {
					area = "马尾区";
				}
				String cost = "0-50";
				if (ds.getCost().intValue() == 2) {
					cost = "50-100";
				}
				if (ds.getCost().intValue() == 2
						|| ds.getCost().intValue() == 3
						|| ds.getCost().intValue() == 4) {
					cost = "100-200";
				}
				if (ds.getCost().intValue() == 8) {
					cost = "200以上";
				}
				String stylevalue = ds.getStylevalue().replaceAll("中餐厅", "")
						.replaceAll("西餐厅", "").replaceAll("亚洲餐厅", "")
						.replaceAll("特色美食", "");
				if (stylevalue.startsWith(",")) {
					stylevalue = stylevalue.replaceFirst(",", "");
				}
				String service = "";
				if (ds.getWifi().intValue() == 1) {
					service = service + "," + "wifi";
				}
				if (ds.getVisa().intValue() == 1) {
					service = service + "," + "刷卡";
				}
				if (ds.getPark().intValue() >= 0) {
					service = service + "," + "车位";
				}
				if (service.startsWith(",")) {
					service = service.replaceFirst(",", "");
				}
				String status = "上线";
				if (ds.getAlive().intValue() == 0) {
					status = "审核中";
				}
				if (ds.getIsnew().intValue() == 0) {
					status = "下线";
				}
				String cd = "";
				List cdlist = this.getDdGoodDAO().findByShopid(ds.getId());
				for (int j = 0; j < cdlist.size(); j++) {
					DdShopgoods dg = (DdShopgoods) cdlist.get(j);
					try {
						Integer.parseInt(dg.getName());
						cd = cd + "|" + "http://www.danding.com/DD/pro_img/"
								+ dg.getId() + "/pic1.jpg";
					} catch (Exception ee) {

					}
				}
				if (cd.startsWith("|")) {
					cd = cd.replaceFirst("\\|", "");
				}
				String hj = "";
				if (ds.getPic3().equals("1")) {
					hj = hj + "|" + "http://www.danding.com/DD/shop_img/"
							+ ds.getId() + "/pic3.jpg";
				}
				if (ds.getPic4().equals("1")) {
					hj = hj + "|" + "http://www.danding.com/DD/shop_img/"
							+ ds.getId() + "/pic4.jpg";
				}
				if (ds.getPic5().equals("1")) {
					hj = hj + "|" + "http://www.danding.com/DD/shop_img/"
							+ ds.getId() + "/pic5.jpg";
				}
				if (ds.getPic6().equals("1")) {
					hj = hj + "|" + "http://www.danding.com/DD/shop_img/"
							+ ds.getId() + "/pic6.jpg";
				}
				if (ds.getPic7().equals("1")) {
					hj = hj + "|" + "http://www.danding.com/DD/shop_img/"
							+ ds.getId() + "/pic7.jpg";
				}
				if (hj.startsWith("|")) {
					hj = hj.replaceFirst("\\|", "");
				}
				String sdh = "";
				if (ds.getIssend().intValue() == 1) {
					sdh = sdh + "," + "送";
				}
				if (ds.getIsbooking().intValue() == 1) {
					sdh = sdh + "," + "订";
				}
				if (ds.getIscoupon().intValue() == 1) {
					sdh = sdh + "," + "惠";
				}
				sdh = sdh.replaceFirst(",", "");
				sbf.append("	" + "福建省/福州市/" + area);
				sbf.append("	" + " ");
				sbf.append("	" + ds.getAddress());
				sbf.append("	" + ds.getPosx() + "/" + ds.getPosy());
				sbf.append("	" + ds.getPosx_g() + "/" + ds.getPosy_g());
				sbf.append("	" + ds.getPhone());
				sbf.append("	" + " ");
				sbf.append("	" + ds.getBossphone());
				sbf.append("	" + ds.getMobile());
				sbf.append("	" + ds.getBus());
				sbf.append("	" + ds.getShophours());
				sbf.append("	" + cost);
				sbf.append("	" + cost);
				sbf.append("	" + ds.getLandmark());
				sbf.append("	" + stylevalue);
				sbf.append("	" + service);
				sbf.append("	"
						+ (ds.getDiscount() == null ? 0 : ds.getDiscount()));
				if (ds.getIssend().intValue() == 1) {
					sbf.append("	" + "送餐费用:" + ds.getSendfee() + " 送餐条件:"
							+ ds.getSendreq());
				} else {
					sbf.append("	" + ds.getBookreq());
				}

				sbf.append("	" + " ");
				sbf.append("	" + " ");
				sbf.append("	" + status);
				sbf.append("	" + ds.getBelong());
				sbf.append("	" + cd);
				sbf.append("	" + hj);
				sbf.append("	" + sdh);
				sbf.append("	" + ds.getUrl());
				System.out.println(sbf.toString());
				if (i % 200 == 0) {
					out.println("200!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 提问,注册用户才能提问(取消.都能提问--)
	// return -1:没登录(取消)
	// 1:成功
	// 2:提问太频繁
	// 3:问题字串太短
	public ActionForward addqa(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ServletContext application = servlet.getServletContext();
		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer("");
		PrintWriter out = response.getWriter();
		DdQaDAO dqd = (DdQaDAO) this.getBean("DdQaDAO");
		Integer logid = (Integer) request.getSession().getAttribute("logid");// 网站用户是否已经登录
		String ipport = request.getRemoteAddr() + request.getRemotePort()
				+ "-q";
		String question = request.getParameter("question");
		if (application.getAttribute(ipport) == null) {
			application.setAttribute(ipport, System.currentTimeMillis());
		} else {
			if ((System.currentTimeMillis() - (Long) application
					.getAttribute(ipport)) < 600000) {
				out
						.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><sign>2</sign></root>");
				return null;
			} else {
				application.setAttribute(ipport, System.currentTimeMillis());
			}
		}
		try {
			if (logid != null) {// 网站用户尚未登录
				DdUser du = this.getDdUserDAO().findById(logid);
				DdQa dq = new DdQa();
				dq.setUserid(logid);
				dq.setQuestion(question);
				dq.setCreatedate(new Date());
				dq.setUsername(du.getLogid());
				if (du.getNickname() != null && du.getNickname().length() > 1) {
					dq.setUsername(du.getNickname());
				}
				dq.setAnswerid(0);
				dqd.saveOrUpdate(dq);
				out.print(sbf.toString());
			} else {
				DdQa dq = new DdQa();
				dq.setUserid(0);
				dq.setQuestion(question);
				dq.setCreatedate(new Date());
				dq.setUsername("游客");
				dq.setAnswerid(0);
				dqd.saveOrUpdate(dq);
				out.print(sbf.toString());

			}
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><sign>1</sign></root>");
			return null;
		} catch (Exception ne) {
			out.print("");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	// 提问,注册用户才能提问(取消.都能提问--)
	// return -1:没登录(取消)
	// 1:成功
	// 2:提问太频繁
	// 3:问题字串太短
	public ActionForward addanswer(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		DdQaDAO dqd = (DdQaDAO) this.getBean("DdQaDAO");
		try {
			int dqid = Integer.parseInt(request.getParameter("id"));
			String answer = request.getParameter("answer");
			Integer logid = (Integer) request.getSession().getAttribute(
					"systemlogid");// 系统用户是否已经登录
			if (logid == null) {
				logid = 999;
			}
			DdQa dq = dqd.findById(dqid);
			dq.setAnswerdate(new Date());
			dq.setAnswer(answer);
			dq.setAnswerid(logid);
			dqd.saveOrUpdate(dq);
			out.print("回答成功!");
			return null;
		} catch (Exception ne) {
			out.print("回答失败!");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward delanswer(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		DdQaDAO dqd = (DdQaDAO) this.getBean("DdQaDAO");
		try {
			int dqid = Integer.parseInt(request.getParameter("id"));
			Integer logid = (Integer) request.getSession().getAttribute(
					"systemlogid");// 系统用户是否已经登录
			if (logid == null) {
				logid = 999;
			}
			DdQa dq = dqd.findById(dqid);
			dqd.delete(dq);
			out.print("删除成功!");
			return null;
		} catch (Exception ne) {
			out.print("删除失败!");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward deldetailr(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			Detailr dr = ldao.findDRById(Integer.parseInt(request
					.getParameter("did")));
			if (dr.getStatus().intValue() == 2) {
				sbf.append("<sign>1</sign>");
				sbf.append("</root>");
				out.print(sbf.toString());
				return null;
			}
			dr.setStatus(2);
			Mainr mr = ldao.findCurMR();
			ldao.saveDetail(dr);
			List drli = ldao.findDRByMR(mr.getId());
			float totalp = 0F;
			int totaldr = 0;
			for (int i = 0; i < drli.size(); i++) {
				Detailr drtmp = (Detailr) drli.get(i);
				if (drtmp.getStatus().intValue() == 2) {
					continue;
				}
				totaldr++;
				totalp = totalp + drtmp.getTotalmoney();
			}
			mr.setTotalnum(totaldr);
			mr.setTotalmoney(totalp);
			mr.setTotalgain(mr.getTotalgain() + dr.getGain());
			ldao.saveMain(mr);
			sbf.append("<sign>1</sign>");
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward kaihao(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			Detailr dr = ldao.findDRById(Integer.parseInt(request
					.getParameter("did")));
			dr.setStatus(1);
			ldao.saveDetail(dr);
			sbf.append("<sign>1</sign>");
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward unkaihao(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			Detailr dr = ldao.findDRById(Integer.parseInt(request
					.getParameter("did")));
			dr.setStatus(0);
			ldao.saveDetail(dr);
			sbf.append("<sign>1</sign>");
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward editdetailr(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			Detailr dr = ldao.findDRById(Integer.parseInt(request
					.getParameter("did")));
			int numcount = Integer.parseInt(request.getParameter("numcount"));
			Mainr mr = ldao.findCurMR();
			dr.setNumindex(Integer.parseInt(request.getParameter("numindex")));
			dr.setPrice(Float.parseFloat(request.getParameter("price")));
			dr.setNumcount(numcount);
			dr.setTotalmoney(dr.getPrice() * (numcount * 1F));
			ldao.saveDetail(dr);
			List drli = ldao.findDRByMR(mr.getId());
			float totalp = 0F;
			int totaldr = 0;
			for (int i = 0; i < drli.size(); i++) {
				Detailr drtmp = (Detailr) drli.get(i);
				if (drtmp.getStatus().intValue() == 2) {
					continue;
				}
				totaldr++;
				totalp = totalp + drtmp.getTotalmoney();
			}
			mr.setTotalnum(totaldr);
			mr.setTotalmoney(totalp);
			ldao.saveMain(mr);
			sbf.append("<sign>1</sign>");
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward adddetailr(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			int numcount = Integer.parseInt(request.getParameter("numcount"));
			Mainr mr = ldao.findCurMR();
			Detailr dr = new Detailr();
			dr.setNumindex(Integer.parseInt(request.getParameter("numindex")));
			dr.setMainid(mr.getId());
			dr.setPrice(Float.parseFloat(request.getParameter("price")));
			dr.setGain(0F);
			dr.setNumcount(numcount);
			dr.setTotalmoney(dr.getPrice() * (numcount * 1F));
			dr.setHis(1);
			ldao.saveDetail(dr);
			List drli = ldao.findDRByMR(mr.getId());
			float totalp = 0F;
			int totaldr = 0;
			for (int i = 0; i < drli.size(); i++) {
				Detailr drtmp = (Detailr) drli.get(i);
				if (drtmp.getStatus().intValue() == 2) {
					continue;
				}
				totalp = totalp + drtmp.getTotalmoney();
				totaldr++;

			}
			mr.setTotalnum(totaldr);
			mr.setTotalmoney(totalp);
			sbf.append("<sign>1</sign>");
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward setcurmainr(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			Mainr mr = ldao.findCurMR();
			mr.setStatus(0);
			int hitnum = 0;
			int totalmrr = 0;
			Mainr mrr = new Mainr();
			mrr.setCreatedate(new Date());
			mrr.setHitnum(0);
			mrr.setFd(0.13F);
			ldao.saveMain(mrr);
			List li = ldao.findDRByMR(mr.getId());
			for (int i = 0; i < li.size(); i++) {
				Detailr dr = (Detailr) li.get(i);
				int status = dr.getStatus();
				if (status == 0) {
					totalmrr++;
					// 没开号,损失=(买入-返点)
					dr.setGain(-1F * dr.getTotalmoney() + dr.getTotalmoney()
							* mr.getFd() + dr.getGain());
					mr.setTotalgain(mr.getTotalgain() + dr.getGain());
					ldao.saveDetail(dr);
					// 没开到的下期继续买.
					Detailr drr = new Detailr();
					drr.setHis(dr.getHis().intValue() + 1);
					drr.setNumcount(dr.getNumcount());

					drr.setMainid(mrr.getId());
					drr.setGain(dr.getGain());
					float p = (10F - drr.getGain())
							/ (41F - dr.getNumcount() * 0.87F);
					drr.setPrice(p);
					drr.setTotalmoney(drr.getPrice() * dr.getNumcount());
					ldao.saveDetail(drr);
				} else {
					// 开号.赚41倍+返点-买入,下期不买了
					dr.setGain(dr.getPrice() * 41F - 1F * dr.getTotalmoney()
							+ dr.getTotalmoney() * (mr.getFd()) + dr.getGain());
					mr.setTotalgain(mr.getTotalgain() + dr.getGain());
					ldao.saveDetail(dr);
					hitnum++;
				}
			}
			mr.setHitnum(hitnum);
			ldao.saveMain(mr);
			/*
			 * if(mr.getTotalgain().floatValue()>0){ //总单赚,把刚刚新建的那些都删了,下棋重新开始 li
			 * = ldao.findDRByMR(mrr.getId()); for(int i=0;i<li.size();i++){ //
			 * Detailr dr = (Detailr)li.get(i); // ldao.delDetail(dr); }
			 * mrr.setTotalgain(0F); mrr.setTotalmoney(0F); }else{
			 * mrr.setTotalgain(mr.getTotalgain()); }
			 */
			mrr.setStatus(1);
			mrr.setTotalgain(mr.getTotalgain());
			mrr.setTotalnum(totalmrr);
			ldao.saveMain(mrr);

			sbf.append("<sign>1</sign></root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward getcurmainr(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			Mainr mr = ldao.findCurMR();
			Mainr lastmr = ldao.findMRById(mr.getId().intValue() - 1);
			if (lastmr != null) {
				sbf.append("<hmainr id=\"" + lastmr.getId()
						+ "\" createdate=\""
						+ DateStrFormat.getCurrentTime(lastmr.getCreatedate())
						+ "\" dan=\"" + lastmr.getTotalnum() + "|"
						+ lastmr.getHitnum() + "\" totalmoney=\""
						+ lastmr.getTotalmoney() + "\" totalgain=\""
						+ lastmr.getTotalgain() + "\" returnback=\""
						+ lastmr.getFd() + "\"  />");
			}
			sbf.append("<mainr id=\"" + mr.getId() + "\" createdate=\""
					+ DateStrFormat.getCurrentTime(mr.getCreatedate())
					+ "\" dan=\"" + mr.getTotalnum() + "\"  totalmoney=\""
					+ mr.getTotalmoney() + "\" totalgain=\""
					+ mr.getTotalgain() + "\" returnback=\"" + mr.getFd()
					+ "\"  />");
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward gethismainr(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			int pageno = Integer.parseInt(request.getParameter("pageno"));
			int pagesize = Integer.parseInt(request.getParameter("pagesize"));
			PageList pl = ldao.findMRPage(pageno, pagesize);
			sbf.append("<mainrs total=\"" + pl.getTotalCount() + "\">");
			for (int i = 0; i < pl.size(); i++) {
				Mainr mr = (Mainr) pl.get(i);
				sbf.append("<mainr id=\"" + mr.getId() + "\" hitnum=\""
						+ mr.getHitnum() + "\" totalmoney=\""
						+ mr.getTotalmoney() + "\" totalgain=\""
						+ mr.getTotalgain() + "\" returnback=\"" + mr.getFd()
						+ "\"  />");
			}
			sbf.append("</mainrs>");
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward detaillist(ActionMapping mapping,
			ActionForm pcUserForm, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>");
		PrintWriter out = response.getWriter();
		try {
			int mid = Integer.parseInt(request.getParameter("mid"));
			LiuDAO ldao = (LiuDAO) this.getBean("LiuDAO");
			List li = ldao.findDRByMR(mid);
			for (int i = 0; i < li.size(); i++) {
				Detailr dr = (Detailr) li.get(i);
				float gain1 = dr.getPrice() * 41F - 1F * dr.getTotalmoney()
						+ dr.getTotalmoney() * (0.13F) + dr.getGain();
				sbf.append("<detailr numindex=\"" + dr.getNumindex()
						+ "\" id=\"" + dr.getId() + "\" his=\"" + dr.getHis()
						+ "\" status=\"" + dr.getStatus() + "\" numcount=\""
						+ dr.getNumcount() + "\" price=\"" + dr.getPrice()
						+ "\" gain=\"" + dr.getGain() + "\" gain1=\"" + gain1
						+ "\" totalprice=\"" + dr.getTotalmoney() + "\" />");
			}
			sbf.append("</root>");
			out.print(sbf.toString());
			return null;
		} catch (Exception ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><error>0</error></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

	public ActionForward getdict(ActionMapping mapping, ActionForm pcUserForm,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		StringBuffer sbf = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"utf-8\"?><root><dicts>");

		PrintWriter out = response.getWriter();
		try {

			String root = request.getParameter("root");
			List list = this.getDictDAO()
					.findByRootNode(Integer.parseInt(root));
			for (int i = 0; i < list.size(); i++) {
				Dict dict = (Dict) list.get(i);
				sbf.append("<dict code=\"" + dict.getNodeCode() + "\" value=\""
						+ dict.getNodeValue() + "\"  />");
			}
			sbf.append("</dicts></root>");
			out.print(sbf.toString());
			return null;
		} catch (NumberFormatException ne) {
			out
					.print("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><sign>20</sign></root>");
			out.flush();
			out.close();
			ne.printStackTrace();
			return null;
		}
	}

}
